﻿#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QDateTime>
#include <QMessageBox>
#include <QNetworkInterface>
#include <QTimer>

#include "TcpServer.h"
#include "TcpClient.h"
#include "UdpSocket.h"
#include "Common/CFormCtrl.h"

#include <Common/QUIHelper.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_itemModelTcpSer(new QStandardItemModel(this))
    , m_itemModelUdpSer(new QStandardItemModel(this))
    , m_timerTcpSer(new QTimer(this))
    , m_timerUdpSer(new QTimer(this))
    , m_timerClient(new QTimer(this))
    , m_tcpServer(new TcpServer())
    , m_tcpClient(new TcpClient())
    , m_udpServer(new UdpSocket())
    , m_udpClient(new UdpSocket())
{
    ui->setupUi(this);

    loadTcpServer();
    connect(m_tcpServer, &TcpServer::sigClientUpdate, this, &MainWindow::onClientUpdateTcp);
    connect(m_tcpServer, &TcpServer::sigReadMsg, this, &MainWindow::onReadMsgTcp);
    connect(m_tcpServer, &TcpServer::sigCNTUpdate, this, &MainWindow::onCNTUpdate);
    connect(m_timerTcpSer, &QTimer::timeout, this, &MainWindow::onTimerTcpSerTimeout);
    emit m_tcpServer->sigClientUpdate();
    emit m_tcpServer->sigCNTUpdate(0, 0);

    loadUdpServer();
    connect(m_udpServer, &UdpSocket::sigClientUpdate, this, &MainWindow::onClientUpdateTcp);
    connect(m_udpServer, &UdpSocket::sigReadMsg, this, &MainWindow::onReadMsgTcp);
    connect(m_udpServer, &UdpSocket::sigCNTUpdate, this, &MainWindow::onCNTUpdate);
    connect(m_timerUdpSer, &QTimer::timeout, this, &MainWindow::onTimerUdpSerTimeout);
    emit m_udpServer->sigClientUpdate();
    emit m_udpServer->sigCNTUpdate(0, 0);

    loadClient();
    connect(m_tcpClient, &TcpClient::sigIsOnline, this, &MainWindow::onTcpClientIsOnline);
    connect(m_tcpClient, &TcpClient::sigReadMsg, this, &MainWindow::onReadMsgTcp);
    connect(m_tcpClient, &TcpClient::sigCNTUpdate, this, &MainWindow::onCNTUpdate);
    connect(m_timerClient, &QTimer::timeout, this, &MainWindow::onTimerClientTimeout);
    emit m_tcpClient->sigCNTUpdate(0, 0);

    connect(m_udpClient, &UdpSocket::sigReadMsg, this, &MainWindow::onReadMsgTcp);
    connect(m_udpClient, &UdpSocket::sigCNTUpdate, this, &MainWindow::onCNTUpdate);
    emit m_udpClient->sigCNTUpdate(0, 0);

    connect(m_tcpServer, &TcpServer::sigSystemLog, this, &MainWindow::onSystemLog);
    connect(m_tcpClient, &TcpClient::sigSystemLog, this, &MainWindow::onSystemLog);
    connect(m_udpServer, &UdpSocket::sigSystemLog, this, &MainWindow::onSystemLog);
    connect(m_udpClient, &UdpSocket::sigSystemLog, this, &MainWindow::onSystemLog);

    ui->tabWidget->setCurrentWidget(ui->tab);
    on_tabWidget_currentChanged(0);

    QPixmap pixmapLogo("./1.png"), pixmapTel("./2.png");
    if (!pixmapLogo.isNull()) {
        ui->label_19->setFixedSize(pixmapLogo.size());
        ui->label_19->setPixmap(pixmapLogo);
    }
    if (!pixmapTel.isNull()) {
        ui->label_20->setPixmap(pixmapTel.scaled(ui->label_20->size(), Qt::KeepAspectRatio));
    }

    resize(1000, 600);
}

MainWindow::~MainWindow()
{
    delete m_itemModelTcpSer;
    delete m_itemModelUdpSer;

    delete m_timerTcpSer;
    delete m_timerUdpSer;
    delete m_timerClient;

    //m_tcpServer->cleanup();
    m_tcpServer->deleteLater();
    //m_udpServer->cleanup();
    m_udpServer->deleteLater();
    //m_tcpClient->cleanup();
    m_tcpClient->deleteLater();
    //m_udpClient->cleanup();
    m_udpClient->deleteLater();

    delete ui;
}

QByteArray MainWindow::formatHexString(const QByteArray &arg, int n, const QString &ch)
{
    QByteArray temp1 = arg.toHex();
    QByteArray temp2;
    for(int i = 0; i < temp1.length() / n; i++) {
        temp2 += temp1.mid(i * n, 2) + ch.toUtf8();
    }

    return temp2;
}

void MainWindow::onTcpClientIsOnline(bool isOnline)
{
    ui->btnConnectSer->setEnabled(!isOnline);
    ui->btnDisconnectSer->setEnabled(isOnline);

    isOnline ? QMessageBox::information(this, "提示", "连接成功！") : QMessageBox::critical(this, "错误", "连接失败！");
}

void MainWindow::onClientUpdateTcp()
{
    if (sender() == m_tcpServer) {
        m_itemModelTcpSer->clear();

        foreach (auto &var, m_tcpServer->getClientList()) {
            m_itemModelTcpSer->appendRow(new QStandardItem (var));
        }

        ui->chkAutoReturnTcpSer->setEnabled(m_itemModelTcpSer->rowCount() >= 1);
        ui->radReturnDataTcpSer->setEnabled(m_itemModelTcpSer->rowCount() >= 1);
        ui->radReturnSelfTcpSer->setEnabled(m_itemModelTcpSer->rowCount() >= 1);
    } else if (sender() == m_udpServer) {
        m_itemModelUdpSer->clear();

        foreach (auto &var, m_udpServer->getClientList()) {
            m_itemModelUdpSer->appendRow(new QStandardItem (var));
        }

        ui->chkAutoReturnUdpSer->setEnabled(m_itemModelUdpSer->rowCount() >= 1);
        ui->radReturnDataUdpSer->setEnabled(m_itemModelUdpSer->rowCount() >= 1);
        ui->radReturnSelfUdpSer->setEnabled(m_itemModelUdpSer->rowCount() >= 1);
    }
}

void MainWindow::onReadMsgTcp(const QString &ip, const QByteArray &msg)
{
    if (sender() == m_tcpServer) {
        //数据回复
        if (ui->chkAutoReturnTcpSer->isChecked()) {
            if (ui->radReturnDataTcpSer->isChecked()) {
                QByteArray msgread = ui->txtSendMsgTcpSer->text().toUpper().toUtf8();
                // 检查发送的文本是否为空
                if (msgread.isEmpty()) {
                    QMessageBox::critical(this, "错误", "发送内容不允许为空！");
                    return;
                }

                // 是否选中了16进制发送的选项
                if (ui->chkSendHexTcpSer->isChecked()) {
                    msgread = QByteArray::fromHex(msgread);
                }
                m_tcpServer->sendMsgToClient(ip, msgread);
            } else {
                m_tcpServer->sendMsgToClient(ip, msg);
            }
        }

        //写入日志
        if (!ui->lvLogTcpSer->model()) {
            ui->lvLogTcpSer->setModel(new QStandardItemModel(this));
        }

        QStandardItemModel *tmp = static_cast<QStandardItemModel *>(ui->lvLogTcpSer->model());
        if (ui->chkDisplayHexTcpSer->isChecked()) {
            tmp->insertRow(0, new QStandardItem (ip + "    " + formatHexString(msg)));
        } else {
            tmp->insertRow(0, new QStandardItem (ip + "    " + msg));
        }

        if (tmp->rowCount() > LOG_ROW_COUNT_MAX) {
            tmp->removeRow(tmp->rowCount() - 1);
        }
    } else if (sender() == m_udpServer) {
        if (!ui->lvLogUdpSer->model()) {
            ui->lvLogUdpSer->setModel(new QStandardItemModel(this));
        }

        QStandardItemModel *tmp = static_cast<QStandardItemModel *>(ui->lvLogUdpSer->model());
        if (ui->chkDisplayHexUdpSer->isChecked()) {
            tmp->insertRow(0, new QStandardItem (ip + "    " + formatHexString(msg)));
        } else {
            tmp->insertRow(0, new QStandardItem (ip + "    " + msg));
        }

        if (tmp->rowCount() > LOG_ROW_COUNT_MAX) {
            tmp->removeRow(tmp->rowCount() - 1);
        }
    } else if (sender() == m_tcpClient || sender() == m_udpClient) {
        if (!ui->lvLogClient->model()) {
            ui->lvLogClient->setModel(new QStandardItemModel(this));
        }

        QStandardItemModel *tmp = static_cast<QStandardItemModel *>(ui->lvLogClient->model());
        if (ui->chkDisplayClient->isChecked()) {
            tmp->insertRow(0, new QStandardItem (ip + "    " + formatHexString(msg)));
        } else {
            tmp->insertRow(0, new QStandardItem (ip + "    " + msg));
        }

        if (tmp->rowCount() > LOG_ROW_COUNT_MAX) {
            tmp->removeRow(tmp->rowCount() - 1);
        }
    }
}

void MainWindow::onCNTUpdate(int send_len, int rev_len)
{
    if (sender() == m_tcpServer) {
        ui->txtSendMsgLenTcpSer->setText(QString::number(send_len));
        ui->txtRevMsgLenTcpSer->setText(QString::number(rev_len));
    } else if (sender() == m_udpServer) {
        ui->txtSendMsgLenUdpSer->setText(QString::number(send_len));
        ui->txtRevMsgLenUdpSer->setText(QString::number(rev_len));
    } else if (sender() == m_tcpClient || sender() == m_udpClient) {
        ui->txtSendMsgLenClient->setText(QString::number(send_len));
        ui->txtRevMsgLenClient->setText(QString::number(rev_len));
    }
}

void MainWindow::onTimerTcpSerTimeout()
{
    // 检查时间设置是否合理
    if (ui->txtSentTimeTcpSer->text().toInt() < 500) {
        ui->chkSentTimeTcpSer->setChecked(false);
        m_timerTcpSer->stop();

        QMessageBox::critical(this, "错误", "发送时间间隔太短！");
        return;
    }

    bool isSucc = sendMsgTcpSer();
    if (!isSucc) {
        ui->chkSentTimeTcpSer->setChecked(false);
        m_timerTcpSer->stop();
    }
}

void MainWindow::onTimerUdpSerTimeout()
{
    // 检查时间设置是否合理
    if (ui->txtSentTimeUdpSer->text().toInt() < 500) {
        ui->chkSentTimeUdpSer->setChecked(false);
        m_timerUdpSer->stop();

        QMessageBox::critical(this, "错误", "发送时间间隔太短！");
        return;
    }

    bool isSucc = sendMsgUdpSer();
    if (!isSucc) {
        ui->chkSentTimeUdpSer->setChecked(false);
        m_timerUdpSer->stop();
    }
}

void MainWindow::onTimerClientTimeout()
{
    // 检查时间设置是否合理
    if (ui->txtSentTimeClient->text().toInt() < 500) {
        ui->chkSentTimeClient->setChecked(false);
        m_timerClient->stop();

        QMessageBox::critical(this, "错误", "发送时间间隔太短！");
        return;
    }

    bool isSucc = false;
    if (ui->comboBox->currentIndex() == 0) {
        isSucc = sendMsgTcpClient();
    } else {
        isSucc = sendMsgUdpClient();
    }

    if (!isSucc) {
        ui->chkSentTimeClient->setChecked(false);
        m_timerClient->stop();
    }
}

void MainWindow::onSystemLog(const QString &log_msg)
{
    if (!ui->lvSystemLog->model()) {
        ui->lvSystemLog->setModel(new QStandardItemModel(this));
    }

    QStandardItemModel *tmp = static_cast<QStandardItemModel *>(ui->lvSystemLog->model());
    tmp->insertRow(0, new QStandardItem (QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss") + "    " + log_msg));
}

void MainWindow::onBtnListenPortClicked()
{
    bool isSucc = false;

    if (sender() == ui->btnListenTcpSer) {
        if (ui->cmbIpTcpSer->currentText() == nullptr || ui->cmbIpTcpSer->currentText().isEmpty()) {
            QUIHelper::setCtrlErrorStyle(ui->cmbIpTcpSer, false);
            QMessageBox::critical(this, "错误", "TCP主机IP 为空");
            return;
        }
        QUIHelper::setCtrlErrorStyle(ui->cmbIpTcpSer, true);

        isSucc = m_tcpServer->listen(QHostAddress(ui->cmbIpTcpSer->currentText()), ui->txtPortTcpSer->text().toInt());
        if (!isSucc) {
            QMessageBox::critical(this, "错误", QString("开启TCP服务器%1:%2失败！").arg(ui->cmbIpTcpSer->currentText()).arg(ui->txtPortTcpSer->text()));
            return;
        }

        ui->btnListenTcpSer->setEnabled(false);
        ui->btnStopListenTcpSer->setEnabled(true);
        ui->cmbIpTcpSer->setEnabled(false);
        ui->txtPortTcpSer->setEnabled(false);
    } else if (sender() == ui->btnListenUdpSer) {
        if (ui->cmbIpUdpSer->currentText() == nullptr || ui->cmbIpUdpSer->currentText().isEmpty()) {
            QUIHelper::setCtrlErrorStyle(ui->cmbIpUdpSer, false);
            QMessageBox::critical(this, "错误", "UDP主机IP 为空");
            return;
        }
        QUIHelper::setCtrlErrorStyle(ui->cmbIpUdpSer, true);

        isSucc = m_udpServer->listen(QHostAddress(ui->cmbIpUdpSer->currentText()), ui->txtPortUdpSer->text().toInt());
        if (!isSucc) {
            QMessageBox::critical(this, "错误", QString("开启UDP服务器%1:%2失败！").arg(ui->cmbIpUdpSer->currentText()).arg(ui->txtPortUdpSer->text()));
            return;
        }

        ui->btnListenUdpSer->setEnabled(false);
        ui->btnStopListenUdpSer->setEnabled(true);
        ui->cmbIpUdpSer->setEnabled(false);
        ui->txtPortUdpSer->setEnabled(false);
    }

    //CFormContrl::setMessageBoxParent(this);
    //CDialog::MessageBoxInfo(this, "ff", "msg");
}

void MainWindow::onBtnStopListenPortClicked()
{
    bool isSucc = false;
    if (sender() == ui->btnStopListenTcpSer) {
        isSucc = m_tcpServer->stopListen();
        if (!isSucc) {
            QMessageBox::critical(this, "错误", "停止TCP服务器失败！");
            return;
        }

        ui->btnListenTcpSer->setEnabled(true);
        ui->btnStopListenTcpSer->setEnabled(false);
        ui->cmbIpTcpSer->setEnabled(true);
        ui->txtPortTcpSer->setEnabled(true);
    } else if (sender() == ui->btnStopListenUdpSer) {
        isSucc = m_udpServer->stopListen();
        if (!isSucc) {
            QMessageBox::critical(this, "错误", "停止UDP服务器失败！");
            return;
        }

        ui->btnListenUdpSer->setEnabled(true);
        ui->btnStopListenUdpSer->setEnabled(false);
        ui->cmbIpUdpSer->setEnabled(true);
        ui->txtPortUdpSer->setEnabled(true);
    }
}

void MainWindow::onBtnDisConnClicked()
{
    if (sender() == ui->btnDisConnTcpSer) {
        QString selItem = ui->lvClientListTcpSer->currentIndex().data().toString();
        if (selItem.isEmpty()) {
            QMessageBox::critical(this, "错误", "请选择需要端口的客户端！");
            return;
        }

        if (m_tcpServer->getClientList().contains(selItem)) {
            m_tcpServer->deleteClient(selItem);
        }
    } else if (sender() == ui->btnDisConnUdpSer) {
        QString selItem = ui->lvClientListUdpSer->currentIndex().data().toString();
        if (selItem.isEmpty()) {
            QMessageBox::critical(this, "错误", "请选择需要端口的客户端！");
            return;
        }

        if (m_udpServer->getClientList().contains(selItem)) {
            m_udpServer->deleteClient(selItem);
        }
    }
}

void MainWindow::onChkSentTimeToggled(bool checked)
{
    if (sender() == ui->chkSentTimeTcpSer) {
        ui->txtSentTimeTcpSer->setEnabled(!checked);

        if (checked) {
            m_timerTcpSer->setInterval(ui->txtSentTimeTcpSer->text().toInt());
            m_timerTcpSer->start();
        } else {
            m_timerTcpSer->stop();
        }
    } else if (sender() == ui->chkSentTimeUdpSer) {
        ui->txtSentTimeUdpSer->setEnabled(!checked);

        if (checked) {
            m_timerUdpSer->setInterval(ui->txtSentTimeUdpSer->text().toInt());
            m_timerUdpSer->start();
        } else {
            m_timerUdpSer->stop();
        }
    } else if (sender() == ui->chkSentTimeClient) {
        ui->txtSentTimeClient->setEnabled(!checked);

        if (checked) {
            m_timerClient->setInterval(ui->txtSentTimeClient->text().toInt());
            m_timerClient->start();
        } else {
            m_timerClient->stop();
        }
    }
}

void MainWindow::onBtnSendClicked()
{
    if (sender() == ui->btnSendTcpSer) {
        sendMsgTcpSer();
    } else if (sender() == ui->btnSendUdpSer) {
        sendMsgUdpSer();
    } else if (sender() == ui->btnSendClient) {
        if (ui->comboBox->currentIndex() == 0) {
            sendMsgTcpClient();
        } else {
            sendMsgUdpClient();
        }
    }
}

void MainWindow::onBtnClearCntClicked()
{
    if (sender() == ui->btnClearCntTcpSer) {
        m_tcpServer->resetCNT();
        emit m_tcpServer->sigCNTUpdate(0, 0);
    } else if (sender() == ui->btnClearCntUdpSer) {
        m_udpServer->resetCNT();
        emit m_udpServer->sigCNTUpdate(0, 0);
    } else if (sender() == ui->btnClearCntClient) {
        if (ui->comboBox->currentIndex() == 0) {
            m_tcpClient->resetCNT();
            emit m_tcpClient->sigCNTUpdate(0, 0);
        } else {
            m_udpClient->resetCNT();
            emit m_udpClient->sigCNTUpdate(0, 0);
        }
    }
}

void MainWindow::onBtnClearRevDataClicked()
{
    if (sender() == ui->btnClearRevDataTcpSer) {
        if (!ui->lvLogTcpSer->model()) {
            ui->lvLogTcpSer->setModel(new QStandardItemModel(this));
        }

        static_cast<QStandardItemModel *>(ui->lvLogTcpSer->model())->clear();
    } else if (sender() == ui->btnClearRevDataUdpSer) {
        if (!ui->lvLogUdpSer->model()) {
            ui->lvLogUdpSer->setModel(new QStandardItemModel(this));
        }

        static_cast<QStandardItemModel *>(ui->lvLogUdpSer->model())->clear();
    } else if (sender() == ui->btnClearRevDataClient) {
        if (!ui->lvLogClient->model()) {
            ui->lvLogClient->setModel(new QStandardItemModel(this));
        }

        static_cast<QStandardItemModel *>(ui->lvLogClient->model())->clear();
    }
}

QList<QString> MainWindow::getHostIpAddress()
{
    QList<QString> tmpList;
    // 这里获取的是本机所有的适配器网络ip
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // 获取第一个本主机的IPv4地址
    int nListSize = ipAddressesList.size();
    for (int i = 0; i < nListSize; ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) {
            tmpList.append(ipAddressesList.at(i).toString());
        }
    }

    tmpList.insert(0, "127.0.0.1");
    return tmpList;
}

void MainWindow::loadTcpServer()
{
    ui->txtPortTcpSer->setText("6800");
    ui->txtPortTcpSer->setValidator(new QIntValidator(ui->txtPortTcpSer));
    ui->txtSentTimeTcpSer->setText("1000");
    ui->txtSentTimeTcpSer->setValidator(new QIntValidator(ui->txtSentTimeTcpSer));

    ui->btnStopListenTcpSer->setEnabled(false);
    ui->radReturnDataTcpSer->setChecked(true);
    ui->lvClientListTcpSer->setModel(m_itemModelTcpSer);    // listview设置Model
    ui->lvClientListTcpSer->setEditTriggers(QAbstractItemView::NoEditTriggers); // 设置不可编译
    ui->lvLogTcpSer->setEditTriggers(QAbstractItemView::NoEditTriggers);        // 设置不可编译

    connect(ui->btnListenTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnListenPortClicked);
    connect(ui->btnStopListenTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnStopListenPortClicked);
    connect(ui->btnDisConnTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnDisConnClicked);

    connect(ui->chkSentTimeTcpSer, &QCheckBox::toggled, this, &MainWindow::onChkSentTimeToggled);

    connect(ui->btnSendTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnSendClicked);
    connect(ui->btnClearCntTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnClearCntClicked);
    connect(ui->btnClearRevDataTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnClearRevDataClicked);
}

void MainWindow::loadUdpServer()
{
    ui->txtPortUdpSer->setText("6900");
    ui->txtPortUdpSer->setValidator(new QIntValidator(ui->txtPortUdpSer));
    ui->txtSentTimeUdpSer->setText("1000");
    ui->txtSentTimeUdpSer->setValidator(new QIntValidator(ui->txtSentTimeUdpSer));

    ui->btnStopListenUdpSer->setEnabled(false);
    ui->radReturnDataUdpSer->setChecked(true);
    ui->lvClientListUdpSer->setModel(m_itemModelUdpSer);    // listview设置Model
    ui->lvClientListUdpSer->setEditTriggers(QAbstractItemView::NoEditTriggers); // 设置不可编译
    ui->lvLogUdpSer->setEditTriggers(QAbstractItemView::NoEditTriggers);        // 设置不可编译

    connect(ui->btnListenUdpSer, &QPushButton::clicked, this, &MainWindow::onBtnListenPortClicked);
    connect(ui->btnStopListenUdpSer, &QPushButton::clicked, this, &MainWindow::onBtnStopListenPortClicked);
    connect(ui->btnDisConnUdpSer, &QPushButton::clicked, this, &MainWindow::onBtnDisConnClicked);

    connect(ui->chkSentTimeUdpSer, &QCheckBox::toggled, this, &MainWindow::onChkSentTimeToggled);

    connect(ui->btnSendUdpSer, &QPushButton::clicked, this, &MainWindow::onBtnSendClicked);
    connect(ui->btnClearCntUdpSer, &QPushButton::clicked, this, &MainWindow::onBtnClearCntClicked);
    connect(ui->btnClearRevDataUdpSer, &QPushButton::clicked, this, &MainWindow::onBtnClearRevDataClicked);
}

void MainWindow::loadClient()
{
    ui->txtServerIp->setText("");
    ui->txtServerPort->setValidator(new QIntValidator(ui->txtServerPort));
    ui->txtSentTimeClient->setText("1000");
    ui->txtSentTimeClient->setValidator(new QIntValidator(ui->txtSentTimeClient));

    ui->lvLogTcpSer->setEditTriggers(QAbstractItemView::NoEditTriggers);        // 设置不可编译

    //    connect(ui->btnListenTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnListenPortClicked);
    //    connect(ui->btnStopListenTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnStopListenPortClicked);
    //    connect(ui->btnDisConnTcpSer, &QPushButton::clicked, this, &MainWindow::onBtnDisConnClicked);

    connect(ui->chkSentTimeClient, &QCheckBox::toggled, this, &MainWindow::onChkSentTimeToggled);

    connect(ui->btnSendClient, &QPushButton::clicked, this, &MainWindow::onBtnSendClicked);
    connect(ui->btnClearCntClient, &QPushButton::clicked, this, &MainWindow::onBtnClearCntClicked);
    connect(ui->btnClearRevDataClient, &QPushButton::clicked, this, &MainWindow::onBtnClearRevDataClicked);
}

bool MainWindow::sendMsgTcpSer()
{
    QList<QString> clientList;
    if (ui->chkSendAllTcpSer->isChecked()) {
        clientList = m_tcpServer->getClientList();
    } else {
        if (!ui->lvClientListTcpSer->currentIndex().data().toString().isEmpty()) {
            clientList.append(ui->lvClientListTcpSer->currentIndex().data().toString());
        }
    }
    // 检查有没有选中客户端
    if (clientList.isEmpty()) {
        QMessageBox::critical(this, "错误", "请选择要发送的目的地！");
        return false;
    }

    QByteArray msg = ui->txtSendMsgTcpSer->text().toUpper().toUtf8();
    // 检查发送的文本是否为空
    if (msg.isEmpty()) {
        QMessageBox::critical(this, "错误", "发送内容不允许为空！");
        return false;
    }

    // 是否选中了16进制发送的选项
    if (ui->chkSendHexTcpSer->isChecked()) {
        msg = QByteArray::fromHex(msg);
    }

    foreach (auto &item, clientList) {
        m_tcpServer->sendMsgToClient(item, msg);
    }

    return true;
}

bool MainWindow::sendMsgUdpSer()
{
    QList<QString> clientList;
    if (ui->chkSendAllUdpSer->isChecked()) {
        clientList.append(getIpAndPortStr(QHostAddress::Broadcast, ui->txtPortUdpSer->text().toInt()));
    } else {
        if (!ui->lvClientListUdpSer->currentIndex().data().toString().isEmpty()) {
            clientList.append(ui->lvClientListUdpSer->currentIndex().data().toString());
        }
    }
    // 检查有没有选中客户端
    if (clientList.isEmpty()) {
        QMessageBox::critical(this, "错误", "请选择要发送的目的地！");
        return false;
    }

    QByteArray msg = ui->txtSendMsgUdpSer->text().toUpper().toUtf8();
    // 检查发送的文本是否为空
    if (msg.isEmpty()) {
        QMessageBox::critical(this, "错误", "发送内容不允许为空！");
        return false;
    }

    // 是否选中了16进制发送的选项
    if (ui->chkSendHexUdpSer->isChecked()) {
        msg = QByteArray::fromHex(msg);
    }

    foreach (auto &item, clientList) {
        m_udpServer->sendMsgToClient(item, msg);
    }

    return true;
}

bool MainWindow::sendMsgTcpClient()
{
    QByteArray msg = ui->txtSendMsgClient->text().toUpper().toUtf8();
    // 检查发送的文本是否为空
    if (msg.isEmpty()) {
        QMessageBox::critical(this, "错误", "发送内容不允许为空！");
        return false;
    }

    // 是否选中了16进制发送的选项
    if (ui->chkSendHexClient->isChecked()) {
        msg = QByteArray::fromHex(msg);
    }

    m_tcpClient->sendMsgToClient(msg);

    return true;
}

bool MainWindow::sendMsgUdpClient()
{
    QByteArray msg = ui->txtSendMsgClient->text().toUpper().toUtf8();
    // 检查发送的文本是否为空
    if (msg.isEmpty()) {
        QMessageBox::critical(this, "错误", "发送内容不允许为空！");
        return false;
    }

    // 是否选中了16进制发送的选项
    if (ui->chkSendHexClient->isChecked()) {
        msg = QByteArray::fromHex(msg);
    }

    m_udpClient->sendMsgToClient(ui->txtServerIp->text(), ui->txtServerPort->text().toInt(), msg);

    return true;
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    switch (index) {
    case 0:
        if (ui->btnListenTcpSer->isEnabled()) {
            ui->cmbIpTcpSer->clear();
            ui->cmbIpTcpSer->addItems(getHostIpAddress());
        }
        break;

    case 1:
        if (ui->btnListenUdpSer->isEnabled()) {
            ui->cmbIpUdpSer->clear();
            ui->cmbIpUdpSer->addItems(getHostIpAddress());
        }
        break;

    case 2:
        break;

    default:
        break;
    }
}

void MainWindow::on_btnConnectSer_clicked()
{
    if (QHostAddress(ui->txtServerIp->text()).toString().isEmpty()) {
        QUIHelper::setCtrlErrorStyle(ui->txtServerIp, false);
        QMessageBox::critical(this, "错误", "IP 不正确");
        return;
    }
    QUIHelper::setCtrlErrorStyle(ui->txtServerIp, true);

    if (ui->comboBox->currentIndex() == 0) {
        m_tcpClient->connectServer(QHostAddress(ui->txtServerIp->text()), ui->txtServerPort->text().toInt());
    } else {
        //m_tcpClient->connectServer(QHostAddress(ui->txtServerIp->text()), ui->txtServerPort->text().toInt());
    }
}

void MainWindow::on_btnDisconnectSer_clicked()
{
    if (ui->comboBox->currentIndex() == 0) {
        m_tcpClient->closeConnect() ? QMessageBox::information(this, "提示", " 断开成功！")
                                    : QMessageBox::critical(this, "错误", "断开失败！");
    } else {
        //m_tcpClient->connectServer(QHostAddress(ui->txtServerIp->text()), ui->txtServerPort->text().toInt());
    }
}
